package org.jeecg.modules.demo.jxcx.service.impl;


import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.demo.jxcx.Utils.R;
import org.jeecg.modules.demo.jxcx.Utils.WXPayAPI;
import org.jeecg.modules.demo.jxcx.service.ITbPayOrdidService;
import org.jeecg.modules.demo.jxcx.service.JxcUserService;
import org.jeecg.modules.demo.jxcx.service.OutpatientService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 门诊服务业务在此处理
 */
@Service("outpatientService")
public class OutpatientServiceImpl implements OutpatientService {

    private static Logger logger = LoggerFactory.getLogger(OutpatientService.class);

    private static String appid = "wx1d9ab11ee22e9e8f";
    private static String mchId = "1684540264";
    private static String notifyUrl = "http://47.108.135.90:8442/wxpay/Payresult";
    private static String wxPayNotifyUrl = "http://47.108.135.90:8442/wxpay/PayRefundresult";
//    private static String mchSerialNo = "3C1F6D1E5FA81A65AFE90572ACEFF4E1F0E06AD1";
    private static String mchSerialNo = "1F00B24FF214F4A49580BFC14EDD952EAD3C88D3";
    private static String apiV3Key = "ZwXH6A8XH5sJTWFJfPJPbS0mQ8x5bhr6";

    @Autowired
    private ITbPayOrdidService iTbPayOrdidService;
    @Autowired
    private JxcUserService jxcUserService;


    @Override
    public R getWxPay(JSONObject params) throws Exception {
        String openid = params.getString("openid");
        String description = params.getString("description");
        String outTradeNo = params.getString("TransactionId");
        String PayFee = params.getString("PayFee");
        logger.info("PayFee========"+PayFee);
//        if (!PayFee.equals("29.9") && !PayFee.equals("39.9") && !PayFee.equals("69.9") && !PayFee.equals("99.9") && !PayFee.equals("239.9") && !PayFee.equals("339.9")){
//            return new R().error("金额不符");
//        }
        String attach = params.getString("attach");
        BigDecimal total = new BigDecimal(PayFee);
        JSONObject commonParams = new JSONObject();
        commonParams.put("mchId",mchId);
        commonParams.put("apiV3Key",apiV3Key);
        commonParams.put("mchSerialNo",mchSerialNo);
        commonParams.put("privateKey",getPrivateKey("C:/Users/Administrator/Desktop/ddy/webapps/cert/apiclient_key.pem"));
        //小程序下单
        String prepayId = WXPayAPI.createOrder(appid, mchId, description, outTradeNo, notifyUrl, total, openid, attach, commonParams);
        //获取小程序调起支付所需的参数
        JSONObject payParams = WXPayAPI.getPayParams(prepayId, appid, getPrivateKey("C:/Users/Administrator/Desktop/ddy/webapps/cert/apiclient_key.pem"));
        String data = params.toString();
        iTbPayOrdidService.savexiadandata(outTradeNo,data,"0");
        return new R().ok(payParams);
    }
    /**
     * 获取私钥。
     *
     * @param filename 私钥文件路径  (required)
     * @return 私钥对象
     */
    public static String getPrivateKey(String filename) throws Exception {
        String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8");
        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");
            return privateKey;

        } catch (Exception e) {
            throw new Exception("无效的密钥格式");
        }
    }
    @Override
    public JSONObject getWxPayRefund(JSONObject params) throws Exception {
        JSONObject commonParams = new JSONObject();
        commonParams.put("privateKey",getPrivateKey("C:/Users/Administrator/Desktop/ddy/webapps/cert/apiclient_key.pem") );
        commonParams.put("mchId", mchId);
        commonParams.put("mchSerialNo", mchSerialNo);
        commonParams.put("apiV3Key", apiV3Key);

        String transactionId ="";

        if (!StringUtils.isBlank(params.getString("payFee"))) {
            String payFee0 = params.getString("payFee");
            String payFee = payFee0.trim();

            // 获取“元”前面的部分
            int index = payFee.indexOf("元");
            String beforeYuan = payFee.substring(0, index);
            params.put("refund",beforeYuan);

        }

        transactionId = params.getString("transaction_id");

        logger.info("transactionId========"+transactionId);
        String outRefundNo = RandomStringUtils.randomNumeric(32);
        String reason = "自费退款";
        logger.info("reason========"+reason);

        JSONObject result = WXPayAPI.refundByTransactionId(transactionId, outRefundNo, reason,
                params.getBigDecimal("refund"), params.getBigDecimal("total"), wxPayNotifyUrl, commonParams);
        return result;
    }

    public static void main(String[] args) throws Exception{
        JSONObject commonParams = new JSONObject();
        commonParams.put("privateKey",getPrivateKey("C:/Users/Administrator/Desktop/ddy/webapps/cert/apiclient_key.pem"));
        commonParams.put("mchId", "1684540264");
        commonParams.put("mchSerialNo", "1F00B24FF214F4A49580BFC14EDD952EAD3C88D3");
        commonParams.put("apiV3Key", "ZwXH6A8XH5sJTWFJfPJPbS0mQ8x5bhr6");

        String refund = "5.94";
        String total = "5.94";
        BigDecimal bigDecimalValue = new BigDecimal(refund);
        BigDecimal totalValue = new BigDecimal(total);
        String transactionId = "4200002139202404114634142566";

        String outRefundNo = RandomStringUtils.randomNumeric(32);
        String reason = "自费退款";
        logger.info("reason========"+reason);


//        JSONObject result = WXPayAPI.refundByOutTradeNo(params.getString("transactionId"), outRefundNo, reason,
//                params.getBigDecimal("refund"), params.getBigDecimal("total"), wxPayNotifyUrl, commonParams);
        JSONObject result = WXPayAPI.refundByTransactionId(transactionId, outRefundNo, reason,
                bigDecimalValue, totalValue, wxPayNotifyUrl, commonParams);

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("refund","6.00");
//        jsonObject.put("total","6.00");
//        jsonObject.put("transaction_id","4200002107202402236743766183");
//        String result = HttpUtils.sendPost("https://glrm.xlhd.cn:8442/palm-hospital/getWxPayRefund", jsonObject);
        System.out.println(result);
    }


    @Override
    public R getWxPayState(JSONObject params) throws Exception {
        String transactionId = params.getString("transaction_id");
        String state = iTbPayOrdidService.selectstateByOutTradeNo(transactionId);
        logger.info("订单"+transactionId+"状态"+state);

        if (!state.equals("2")){
            int count = 1;
            Boolean cx =  queryPayStatus(transactionId,count);
            if(cx) {
                iTbPayOrdidService.updatestate("2",transactionId);
                String type = params.getString("type");
                String paytype = params.getString("paytype");
                JSONObject json = new JSONObject();
                if (paytype.equals("续费")){
                    json.put("id",params.getString("id"));
                    json.put("datetype",type);
                    return jxcUserService.exdate(json);
                }else if (paytype.equals("开通")){
                    JSONObject xiadandata =JSONObject.parseObject(iTbPayOrdidService.selectdataByOutTradeNo(transactionId));
                    json.put("phone",xiadandata.getString("phone"));
                    json.put("account",xiadandata.getString("phone"));
                    json.put("companyId",xiadandata.getString("companyId"));
                    json.put("name",xiadandata.getString("name"));
                    json.put("password","123456");
                    json.put("datetype",type);
                    json.put("jurisdiction",xiadandata.getString("jurisdiction"));
                    return jxcUserService.add(json);
                }
            }else {
                iTbPayOrdidService.updatestate("1",transactionId);
                return new R().error("支付失败");
            }
        }
        return new R().ok("支付成功");
    }


    public boolean queryPayStatus(String TransactionId, int count){
        JSONObject param = new JSONObject();
        if(count > 10) {
            logger.info("自费支付订单查询【" + TransactionId + "】======失败 超过10次");
            return false;
        }
        try {
            logger.info("自费支付订单查询【" + TransactionId + "】==========第【" + count + "】次支付订单查询==========");

            JSONObject commonParams = new JSONObject();
            commonParams.put("privateKey",getPrivateKey("C:/Users/Administrator/Desktop/ddy/webapps/cert/apiclient_key.pem") );
            commonParams.put("mchId", mchId);
            commonParams.put("mchSerialNo", mchSerialNo);
            commonParams.put("apiV3Key", apiV3Key);

            JSONObject result = WXPayAPI.queryOrderByOutTradeNo(TransactionId, mchId, commonParams);
//            if (!result.getString("trade_state").equals("SUCCESS")){
//                throw new Exception("支付失败");
//            }
            String t = result.getString("trade_state");
//            String t = iTbPayOrdidService.selectstateByOutTradeNo(TransactionId);

            logger.info("自费支付订单查询【" + TransactionId + "】==========第【" + count + "】次支付订单查询==========");
            if (t.equals("SUCCESS")){
                logger.info("自费支付订单查询【" + TransactionId + "】==========成功");
                return true;

            }else {
                logger.info("自费支付订单查询【" + TransactionId + "】==========失败");
                Thread.sleep(1000);
                count++;
                return  this.queryPayStatus(TransactionId, count);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("自费支付订单查询【" + TransactionId + "】================,订单查询出错，" +  e.getMessage());
            return false;
        }
    }


}
